package org.ai.demo.auth.config;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;


public class CustomerAccessTokenConverter implements TokenEnhancer {
	
	private Logger logger = LoggerFactory.getLogger(CustomerAccessTokenConverter.class);
	
	private ClientDetailsService clientDetailsService;
	
	public CustomerAccessTokenConverter(ClientDetailsService clientDetailsService) {
		this.clientDetailsService = clientDetailsService;
	}

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
//		final Map<String, Object> additionalInfo = new HashMap<>();
		String token = accessToken.getValue();
		Object principal = authentication.getPrincipal();
		ClientDetails clientDetails = clientDetailsService.loadClientByClientId((String)principal);
		String clientId = encryptBASE64((String)principal); 
		String clientSecret = encryptBASE64(clientDetails.getClientSecret());
		String newToken = token + "." + clientId + "." + clientSecret;
		((DefaultOAuth2AccessToken) accessToken).setValue(newToken);
		return accessToken;
	}
	
	private  String encryptBASE64(String key){
		final Base64.Encoder encoder = Base64.getEncoder();
		byte[] textByte;
		String encodedText = null;
		try {
			textByte = key.getBytes("UTF-8");
			encodedText = encoder.encodeToString(textByte);
		} catch (UnsupportedEncodingException e) {
			logger.error("CustomerAccessTokenConverter:encryptBASE64 " + e.getMessage());
		}
        return encodedText;
    }

}
	